﻿using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 测试2
{
    public partial class Form1 : Form
    {
        DataTable sizes;
        public Form1()
        {
            InitializeComponent();
        }
        modelData md = new modelData();
        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建报表参数（名字要和 RDLC 里定义的一致）
            var parameters = new List<ReportParameter>
{
    new ReportParameter("time", DateTime.Now.ToString()),//报告时间
    new ReportParameter("type", "12"),//仪器型号
    new ReportParameter("name", "34"),//样品名称
    new ReportParameter("location", "56"),//取样位置
    new ReportParameter("number", "78"),//样品编号
    new ReportParameter("timeNow", DateTime.Now.ToString()),//样品编号
    new ReportParameter("no", "90"),//样品批次
    new ReportParameter("volume", "5"),//测试体积
    new ReportParameter("Einheit", "总数"),//测试体积
    new ReportParameter("count", "3")//测试次数
};
            // 把参数绑定到报表
            reportViewer1.LocalReport.SetParameters(parameters);
            this.reportViewer1.RefreshReport();



            var tests = md.CreateTestsTable();
            tests.Rows.Add(1, "1", DateTime.Parse("2025-10-17 09:20:01"), 5.0);
            tests.Rows.Add(2, "2", DateTime.Parse("2025-10-17 09:20:01"), 5.0);
            tests.Rows.Add(3, "3", DateTime.Parse("2025-10-17 09:20:01"), 5.0);

            sizes = md.CreateSizesTable();
            Console.WriteLine("sizes 列数: " + sizes.Columns.Count);
            sizes.Rows.Add(1, "0.1", 1789.20, 733.07, 5.0, 3.0, 15.66, 16.77, 41.11, 51.99, 77.88, 99.11, 515.48, 948.162);
            sizes.Rows.Add(1, "0.2", 1056.13, 455.11, 4.0, 3.0, 15.66, 16.77, 41.11, 51.99, 77.88, 99.11, 515.48, 948.162);
            sizes.Rows.Add(1, "0.3", 1056.13, 455.11, 5.0, 3.0, 15.66, 16.77, 41.11, 51.99, 77.88, 99.11, 515.48, 948.162);
            sizes.Rows.Add(1, "0.4", 1056.13, 455.11, 2.0, 3.0, 15.66, 16.77, 41.11, 51.99, 77.88, 99.11, 515.48, 948.162);
            sizes.Rows.Add(1, "0.5", 1056.13, 455.11);


            sizes.Rows.Add(2, "0.1", 1800.0, 740.0);
            sizes.Rows.Add(2, "0.2", 1100.0, 460.0);
            sizes.Rows.Add(2, "0.4", 1056.13, 455.11, 2.0, 3.0, 15.66, 16.77, 481.11, 516.99, 77.88, 99.11, 515.48, 948.162);

            sizes.Rows.Add(3, "0.1", 1750.0, 720.0);
            sizes.Rows.Add(3, "0.2", 1050.0, 450.0);
            sizes.Rows.Add(3, "0.4", 1056.13, 455.11, 2.0, 3.0, 15.66, 16.77, 481.11, 516.99, 77.88, 99.11, 515.48, 948.162);


            // ... 按需填充所有行

            var averages = md.CreateAveragesTable();
            // 计算并填充 averages（示例）
            averages.Rows.Add("0.1", 1722.20, 722.07);
            averages.Rows.Add("0.2", 1033.13, 433.11);


            reportViewer1.LocalReport.DataSources.Clear();
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("TestsDataSet", tests));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("AveragesDataSet", averages));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("SizesDataSet", sizes));
            //reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("AnalyseDataSet", ana));
            // SizesDataSet 不直接绑定到主报表，这个会在 SubreportProcessing 里按 TestID 提供
            reportViewer1.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
            reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
            reportViewer1.ZoomMode = ZoomMode.PageWidth;
            reportViewer1.RefreshReport();



            // 测试打印主报表数据
            Console.WriteLine("=== TestsDataSet ===");
            foreach (DataRow row in tests.Rows)
            {
                Console.WriteLine($"TestID={row["TestID"]}, TestOrder={row["TestOrder"]}, TestTime={row["TestTime"]}, Volume={row["TestVolume"]}");
            }

        }
        private int subreportCallCount = 0;

        private void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
            Console.WriteLine("=== 子报表处理开始 ===");

            try
            {
                // 使用调用顺序来确定 TestID
                int testId = (subreportCallCount % 3) + 1; // 循环使用 1, 2, 3

                Console.WriteLine($"调用次数: {subreportCallCount + 1}, 使用 TestID: {testId}");

                var rows = sizes.AsEnumerable().Where(r => r.Field<int>("TestID") == testId);
                Console.WriteLine($"找到 {rows.Count()} 条记录");

                // 创建新的数据表，确保列名正确
                DataTable filtered = sizes.Clone();
                foreach (var row in rows)
                {
                    filtered.ImportRow(row);
                    Console.WriteLine($"添加: TestID={row.Field<int>("TestID")}, Size={row.Field<string>("Size")}");
                }

                // 确保数据源名称与子报表中使用的名称一致
                e.DataSources.Add(new ReportDataSource("SizesDataSet", filtered)); // 注意：这里使用 SizesDataSet
            }
            catch (Exception ex)
            {
                Console.WriteLine($"子报表处理错误: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                // 返回空数据表
                e.DataSources.Add(new ReportDataSource("SizesDataSet", sizes.Clone()));
            }

            subreportCallCount++;
            Console.WriteLine("=== 子报表处理结束 ===");
            
        }

        private void ExportReportToPdf()
        {
            try
            {
                Warning[] warnings;
                string[] streamIds;
                string mimeType;
                string encoding;
                string extension;

                byte[] bytes = reportViewer1.LocalReport.Render(
                    "PDF", null, out mimeType, out encoding,
                    out extension, out streamIds, out warnings);

                string outputDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Export");
                if (!Directory.Exists(outputDir))
                    Directory.CreateDirectory(outputDir);

                string filePath = Path.Combine(outputDir, $"Report_{DateTime.Now:yyyyMMdd_HHmmss}.pdf");

                File.WriteAllBytes(filePath, bytes);

                MessageBox.Show($"PDF 导出成功：\n{filePath}", "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"PDF 导出失败：{ex.Message}");
            }
        }
        private void reportViewer1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportReportToPdf();
        }
    }
}
